package edu.njit.hz278.core.web;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

/**
 * 
 * @author Rivers Zhang
 *
 */
public class BindingResult {

	private int size = 0;
	private Map<String, Map<String, String>> set = new HashMap<>();
	private static final Validator validator = Validation
			.buildDefaultValidatorFactory().getValidator();

	public int getErrorAmount() {
		return size;
	}
	
	public boolean hasError() {
		return set.size() != 0;
	}

	public boolean validate(String name, Object obj) {
		Set<ConstraintViolation<Object>> cv = validator.validate(obj);
		if (cv.size() > 0) {
			Map<String, String> singleBean = new HashMap<>();
			for(ConstraintViolation<Object> e : cv)
				singleBean.put(e.getPropertyPath().toString(), e.getMessage());
			size += cv.size();
			set.put(name, singleBean);
			return false;
		}
		return true;
	}

	public boolean validate(Object obj) {
		return validate(obj.getClass().getSimpleName(), obj);
	}

	public Map<String, Map<String, String>> getErrors() {
		return set;
	}
	
	Map<String, Object> wrapErrors() {
		Map<String, Object> ret = new HashMap<>();
		ret.put("msg", "oops");
		ret.putAll(getErrors());
		return ret;
	}

}
